package org.jackysoft.file;

import java.util.concurrent.Callable;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.jackysoft.config.CommonConfiguration;
import org.jackysoft.entity.UploadedFileItem;
import org.jackysoft.entity.User;
import org.jackysoft.util.FileInfo;
import org.jackysoft.util.StringUtils;
import org.joda.time.DateTime;

public class FileSaver implements Callable<FileInfo> {
	static final Log logger = LogFactory.getLog(FileSaver.class);
	private byte[] fileData;
	private CommonConfiguration config;
	private String extName;
	private User owner;
    private Session session;
    private String folderId;
    private String title;

	public FileSaver(byte[] fileData, CommonConfiguration config, String extName, User owner, Session session, String folderId,String title) {
		super();
		this.fileData = fileData;
		this.config = config;
		this.extName = extName;
		this.owner = owner;
		this.session = session;
		this.folderId = folderId;
		this.title = title;
	}


	@Override
	public FileInfo call() throws Exception {
		return save();
	}
	
	public FileInfo save() throws Exception {
		FileInfo fi  =new FileAdapter(fileData, title,owner,config.getDiskBase()).save();
		UploadedFileItem upfile = new UploadedFileItem();
		upfile.setDiskBase(config.getDiskBase());
		upfile.setFileType(extName);
		upfile.setRealName(fi.getRealPath());
		upfile.setTitle(StringUtils.splitPreFileName(title));
		upfile.setOwner(owner);
		upfile.setImgpath("images/fileico/" + extName + ".jpg");
		upfile.setCreateTime(DateTime.now());
		upfile.setFolder(folderId);
		fi.setTitle(title);
		session.save(upfile);
		logger.info(title+"  插入, "+upfile.getCreateTime().toString());
		return fi;
	}

}
